/*
反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题？

*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 /*
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL){
            return head;
        }
        ListNode* last=new ListNode(head->val);
        last->next=NULL;
        ListNode* cur=head->next;
        ListNode* tmp=NULL;
        while(cur!=NULL){
            tmp=new ListNode(cur->val);
            tmp->next=last;
            last=tmp;
            cur=cur->next;
        }
        return last;
    }
};
*/

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* last=NULL;
        ListNode* cur=head;
        ListNode* next=NULL;
        while(cur!=NULL){
            next=cur->next;
            cur->next=last;
            last=cur;
            cur=next;
        }
        return last;
    }
};

// 2020.8.11 town
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        stack<ListNode*> mystack;
        ListNode* cur = head;
        while (cur != NULL) {
            mystack.push(cur);
            cur = cur -> next;
        }
        ListNode* res = new ListNode(0);
        ListNode* tmp = res;
        while (!mystack.empty()) {
            tmp -> next = mystack.top();
            tmp = mystack.top();
            mystack.pop();
        }
        tmp -> next =NULL;
        return res -> next;
    }
};